import { Component, OnInit, ViewChild } from '@angular/core'
import { UserAuthService } from 'src/app/@core/user-auth.service'
import { ToastService } from 'ng-devui'
import { Router } from '@angular/router'
import { ManageService } from 'src/app/@core/manage.service'
import { HeaderComponent } from 'src/app/@shared/components/header/header.component'
import { Store } from '@ngrx/store'
import { AvatarState } from 'src/app/store'

@Component({
  selector: 'app-base-user-info',
  templateUrl: './base-user-info.component.html',
  styleUrls: ['./base-user-info.component.scss']
})
export class BaseUserInfoComponent implements OnInit {
  @ViewChild(HeaderComponent) public header!: HeaderComponent
  userName: string
  address: string
  createdTime: string
  authenticated: string
  phoneConnect: string
  phone: string
  userId = parseInt(localStorage.getItem('userId'))
  role = localStorage.getItem('ROLE')
  msgs: Array<Object> = []
  fileUrlObsKey: any
  img: any
  defaultImg = '../../assets/img/default.png'

  constructor(
    private userAuthService: UserAuthService,
    private router: Router,
    private toastService: ToastService,
    public manageService: ManageService,
    private store: Store<AvatarState>
  ) { }

  ngOnInit(): void {
    this.getUserMessage()
  }

  getUserMessage() {
    this.userAuthService.getUserMessage().subscribe((res) => {
      this.userName = res.data.userName
      this.address = res.data.address
      this.createdTime = this.timeTransform(res.data.createdTime)
      this.authenticated = res.data.authenticated === true ? '已认证' : '未认证'
      this.phoneConnect = res.data.regPhoneNum !== '' ? '已绑定' : '未绑定'
      this.phone = res.data.regPhoneNum
      this.img = res.data.profilePhotoUrl
    })
  }

  showToast(type: any, title: string, msg: string) {
    this.msgs = [{ severity: type, summary: title, detail: msg }]
  }

  fileChange(e) {
    var file = e.target.files[0]
    var formData = new FormData()
    if (!file.type.includes('image')) {
      this.showToast('error', '', '请选择图片！')
      return false
    }
    if (file.size > 10 * 1024 * 1024) {
      this.showToast('error', '', '不能超过10M！')
      return false
    }
    formData.append('file', file)
    var user = localStorage.getItem('userId')
    formData.append('userId', user)

    if (e.target.files[0]) {
      var reader = new FileReader()
      if (file.type.indexOf('image') != -1) {
        reader.readAsDataURL(file)
        reader.onload = () => {
          this.img = reader.result
        }
      }
      this.userAuthService.uploadAvatar(formData).subscribe((res) => {
        this.fileUrlObsKey = res.data?.obsKey
        if (this.fileUrlObsKey) {
          this.store.dispatch({
            type: 'AVATAR',
            payload: this.fileUrlObsKey
          })
        }
      })
    }
  }

  uploadFile() {
    document.getElementById('avatarFile').click()
  }

  userVerification() {
    this.userAuthService.getUserVerification(this.userId).subscribe((res) => {
      if (res.code == 0 && res.data == false) {
        this.router.navigate(['/userVerification'])
      } else {
        this.getUserMessage()
      }
    })
  }

  routeNavigateModify() {
    this.router.navigate(['./baseUserInfo/passwordModify'], { queryParams: { userId: this.userId } })
  }

  routeNavigateLogoff() {
    this.router.navigate(['./baseUserInfo/logoff'], { queryParams: { userName: this.userName } })
  }

  connectPhone() {
    this.userAuthService.checkTele(this.userId).subscribe((res) => {
      if (res.code == 0)
        if (res.data == false) {
          this.router.navigate(['/baseUserInfo/telephoneConnect'], { queryParams: { type: true } })
        }
        else {
          this.router.navigate(['/baseUserInfo/telephoneConnect'], { queryParams: { type: false } })
        }
    })
  }

  getImg(type) {
    if ((type == 'password') || (type == '已认证') || (type == '已绑定')) {
      return '../../assets/img/login/success.svg'
    }
    else {
      return '../../assets/img/login/warning.svg'
    }
  }

  copyId(id: string) {
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(id).then(() => {
        this.toastService.open({ value: [{ severity: 'success', summary: '', content: '复制成功' }] });
      }, () => {
      })
    } else {
      let textArea = document.createElement("textarea");
      textArea.value = id;
      textArea.style.position = "absolute";
      textArea.style.opacity = '0';
      textArea.style.left = "-999999px";
      textArea.style.top = "-999999px";
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      new Promise((res, rej) => {
        // 执行复制命令并移除文本框
        document.execCommand('copy') ? this.toastService.open({ value: [{ severity: 'success', summary: '', content: '复制成功' }] }) : rej;
        textArea.remove();
      })
    }
  }

  timeTransform(time) {
    var date = new Date(time)
    var Y = date.getFullYear() + '-'
    var M =
      (date.getMonth() + 1 < 10
        ? "0" + (date.getMonth() + 1)
        : date.getMonth() + 1) + "-";
    var D =
      (date.getDate() < 10
        ? "0" + (date.getDate())
        : date.getDate()) + " ";

    var h = date.getHours() > 9 ? date.getHours() : "0" + date.getHours();
    var m = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes();
    var s = date.getSeconds() > 9 ? date.getSeconds() : "0" + date.getSeconds();
    return Y + M + D + h + ":" + m + ":" + s;
  }
}
